package cn.sunxiansheng.redis.controller;

import cn.sunxiansheng.redis.utils.RString;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Description: 测试 RString 工具类的 Controller
 *
 * @Author sun
 * @Create 2024/11/14 15:20
 * @Version 1.0
 */
@RestController
@RequestMapping("/rstring")
public class RStringController {

    @Resource
    private RString rString;

    /**
     * 设置缓存值
     */
    @PostMapping("/set")
    public String set(@RequestParam String key, @RequestParam Long value) {
        rString.set(key, value);
        return "Value set successfully!";
    }

    /**
     * 设置缓存值并设置过期时间
     */
    @PostMapping("/setWithExpire")
    public String setWithExpire(@RequestParam String key,
                                @RequestParam Long value,
                                @RequestParam long timeout) {
        rString.setWithExpire(key, value, timeout);
        return "Value set with expiration successfully!";
    }

    /**
     * 设置缓存值并设置过期时间（自定义时间单位）
     */
    @PostMapping("/setWithExpireUnit")
    public String setWithExpireUnit(@RequestParam String key,
                                    @RequestParam Long value,
                                    @RequestParam long timeout) {
        rString.setWithExpire(key, value, timeout, TimeUnit.DAYS);
        return "Value set with custom expiration successfully!";
    }

    /**
     * 设置缓存值，如果key不存在，则设置成功
     */
    @PostMapping("/setIfAbsent")
    public String setIfAbsent(@RequestParam String key,
                              @RequestParam Long value,
                              @RequestParam long timeout) {
        boolean result = rString.setIfAbsent(key, value, timeout);
        return result ? "Value set successfully!" : "Key already exists!";
    }

    /**
     * 获取缓存值
     */
    @GetMapping("/get")
    public Long get(@RequestParam String key) {
        return rString.get(key, Long.class);
    }

    /**
     * 获取缓存值并设置新值
     */
    @PostMapping("/getAndSet")
    public Long getAndSet(@RequestParam String key, @RequestParam Long value) {
        return rString.getAndSet(key, value, Long.class);
    }

    /**
     * 根据 delta 值调整缓存中的数值
     */
    @PostMapping("/changeByDelta")
    public Long changeByDelta(@RequestParam String key, @RequestParam long delta) {
        return rString.changeByDelta(key, delta);
    }
}